/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lucava.boatskeeper.client.view;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import gwtupload.client.IUploadStatus;
import gwtupload.client.IUploader;
import gwtupload.client.MultiUploader;
import gwtupload.client.PreloadedImage;
import java.util.List;
import org.lucava.boatskeeper.client.event.boat.CancelEditBoatEvent;
import org.lucava.boatskeeper.client.event.boat.SaveBoatEvent;
import org.lucava.boatskeeper.shared.dto.BoatDto;
import org.lucava.boatskeeper.shared.dto.BoatImageDto;
import org.lucava.boatskeeper.shared.dto.CategoryDto;
import org.lucava.lib.client.view.MvcView;

/**
 *
 * @author glenn
 */
public class BoatEditView extends MvcView {

    private final TextBox displayName;
    private final Label displayNameMessage;
    private final ListBox categoryBox;
    private final TextArea description;
    private final TextBox latBox;
    private final Label latMessage;
    private final Label longMessage;
    private final TextBox longBox;
    private final Label descriptionNameMessage;
    private final FlexTable detailsTable;
    private final Button saveButton;
    private final Button cancelButton;
    private final MultiUploader defaultUploader;
    private Panel imagePanel;
    private final PreloadedImage.OnLoadPreloadedImageHandler showImage = new PreloadedImage.OnLoadPreloadedImageHandler() {
        @Override
        public void onLoad(PreloadedImage image) {
            image.setWidth("75px");
            imagePanel.clear();
            imagePanel.add(image);
        }
    };
    private BoatDto boat;
    private List<CategoryDto> categories;

    public BoatEditView(EventBus eventBus) {
        super(eventBus);

        displayName = new TextBox();
        displayName.setMaxLength(254);
        displayNameMessage = new Label();

        description = new TextArea();
        descriptionNameMessage = new Label();

        latBox = new TextBox();
        latMessage = new Label();
        longBox = new TextBox();
        longMessage = new Label();

        resetMessages();

        categoryBox = new ListBox();
        imagePanel = new SimplePanel();

        DecoratorPanel contentDetailsDecorator = new DecoratorPanel();
        contentDetailsDecorator.setWidth("40em");
        initWidget(contentDetailsDecorator);

        VerticalPanel contentDetailsPanel = new VerticalPanel();
        contentDetailsPanel.setWidth("100%");

        // Create the boats list
        //
        detailsTable = new FlexTable();
        detailsTable.setCellSpacing(2);
        detailsTable.setWidth("100%");
        detailsTable.addStyleName("boat-edit-table");


        defaultUploader = new MultiUploader();
        defaultUploader.setMaximumFiles(1);

        initDetailsTable();


        HorizontalPanel menuPanel = new HorizontalPanel();



        saveButton = new Button("Save", new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                resetMessages();
                getEventBus().fireEvent(new SaveBoatEvent());
            }
        });


        cancelButton = new Button("Cancel", new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                getEventBus().fireEvent(new CancelEditBoatEvent());
            }
        });


        menuPanel.add(saveButton);
        menuPanel.add(cancelButton);

        contentDetailsPanel.add(detailsTable);
        contentDetailsPanel.add(menuPanel);
        contentDetailsDecorator.add(contentDetailsPanel);


        defaultUploader.addOnFinishUploadHandler(new IUploader.OnFinishUploaderHandler() {
            @Override
            public void onFinish(IUploader uploader) {
                if (uploader.getStatus() == IUploadStatus.Status.SUCCESS) {
                    PreloadedImage preloadedImage = new PreloadedImage("images/" + uploader.getFileName(), showImage);
                    IUploader.UploadedInfo info = uploader.getServerInfo();
                }
            }
        });
    }

    private void initDetailsTable() {
        detailsTable.setWidget(0, 0, new Label("Nom"));
        detailsTable.setWidget(0, 1, displayName);
        detailsTable.setWidget(0, 2, displayNameMessage);
        detailsTable.setWidget(1, 0, new Label("Catégorie"));
        detailsTable.setWidget(1, 1, categoryBox);
        detailsTable.setWidget(2, 0, new Label("Aperçu"));
        detailsTable.setWidget(2, 1, imagePanel);
        detailsTable.setWidget(3, 0, new Label("Image"));
        detailsTable.setWidget(3, 1, defaultUploader);
        detailsTable.setWidget(4, 0, new Label("Latitude"));
        detailsTable.setWidget(4, 1, latBox);
        detailsTable.setWidget(4, 2, latMessage);
        detailsTable.setWidget(5, 0, new Label("Longitude"));
        detailsTable.setWidget(5, 1, longBox);
        detailsTable.setWidget(5, 2, longMessage);
        detailsTable.setWidget(6, 0, new Label("Description"));
        detailsTable.setWidget(6, 1, description);
        detailsTable.setWidget(6, 2, descriptionNameMessage);
        displayName.setFocus(true);
    }

    public BoatDto getBoat() {
        if (boat == null) {
            boat = new BoatDto();
        }
        //MAJ du modele
        boat.setName(displayName.getText());
        boat.setDescription(description.getText());
        NumberFormat fmt = NumberFormat.getDecimalFormat();
        boat.setLatitude(new Float(fmt.parse(latBox.getText())));
        boat.setLongitude(new Float(fmt.parse(longBox.getText())));
        boat.setBoatImage(new BoatImageDto(defaultUploader.getFileName(), "images/" + defaultUploader.getFileName()));

        boat.getCategory().setId(Integer.parseInt(categoryBox.getValue(categoryBox.getSelectedIndex())));

        return this.boat;
    }

    public void setBoat(BoatDto result) {
        boat = result;

        //MAJ des champs
        displayName.setText(result.getName());
        description.setText(result.getDescription());
        NumberFormat fmt = NumberFormat.getDecimalFormat();
        if (result.getLongitude() != null && result.getLatitude() != null) {
            longBox.setText(fmt.format(result.getLongitude()));
            latBox.setText(fmt.format(result.getLatitude()));
        }
        selectCategory(result.getCategory());

        //MAJ  images
        defaultUploader.clear();
        imagePanel.clear();
        if (result.getBoatImage().getUrl() == null) {
            result.getBoatImage().setUrl("images/default_boat.jpg");
        }
        new PreloadedImage(result.getBoatImage().getUrl(), showImage);

    }

    public void setCategories(List<CategoryDto> result) {
        categoryBox.clear();
        this.categories = result;
        for (CategoryDto cat : result) {
            categoryBox.addItem(cat.getName(), cat.getId().toString());
        }
    }

    public void selectCategory(CategoryDto select) {
        if (this.categories != null) {

            for (CategoryDto cat : this.categories) {
                if (cat.getId() == select.getId()) {
                    categoryBox.setSelectedIndex(this.categories.indexOf(cat));
                    break;
                }
            }

        }
    }

    private void resetMessages() {
        displayNameMessage.setStyleName("red-text");
        displayNameMessage.setText("");
        displayNameMessage.setVisible(false);

        descriptionNameMessage.setStyleName("red-text");
        descriptionNameMessage.setText("");
        descriptionNameMessage.setVisible(false);

        latMessage.setStyleName("red-text");
        latMessage.setText("");
        latMessage.setVisible(false);

        longMessage.setStyleName("red-text");
        longMessage.setText("");
        longMessage.setVisible(false);
    }

    public Boolean isValid() {

        Boolean isValid = true;

        if (!latBox.getText().matches("[\\-]?[0-9]+.[0-9]+")) {
            latMessage.setVisible(true);
            latMessage.setText("format incorrect");
            isValid = false;
        }

        if (!longBox.getText().matches("[\\-]?[0-9]+.[0-9]+")) {
            longMessage.setVisible(true);
            longMessage.setText("format incorrect");
            isValid = false;
        }

        if (!displayName.getText().matches(".{4,254}")) {
            displayNameMessage.setVisible(true);
            displayNameMessage.setText("minimum 4 caractères");
            isValid = false;
        }

        if (!description.getText().matches(".{4,}")) {
            descriptionNameMessage.setVisible(true);
            descriptionNameMessage.setText("description obligatoire");
            isValid = false;
        }
        return isValid;

    }
}
